#include "PanoHelper.h"
#include <tchar.h>
#include <Wininet.h>  
#include <stdio.h>
#include "Markup.h"

#pragma comment(lib, "Wininet.lib")

CPanoHelper::CPanoHelper()
{
}


CPanoHelper::~CPanoHelper()
{
}

VOID CPanoHelper::RegisterPanoExe(LPCTSTR pano_exe_path)
{
	SHELLEXECUTEINFO ShExecInfo = { 0 };
	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
	ShExecInfo.hwnd = NULL; 
	ShExecInfo.lpVerb = NULL;
	ShExecInfo.lpFile = pano_exe_path;
	ShExecInfo.lpParameters = _T("register \"ruza4tk2X4MdHuE7djJQGr9QTftMFHiSH2ac5jkIlFgGqG0K0IVQnh5vF/cicLpwedsURI0QTg+UluEgysRLUytpeVFyBTxdwREEIGquRh1Hp2BY2EtZ8kdO2r6CHLJAFlzY5w6au1rnHwRhJXgaK8J75RwK1DYb/OEZ4tD2pniUrnMrpFwGWwcKnxGyNSmMktsU6qadFjKbMH3HUKNXa7Y59lEzbDZJbsTuP+UynwwBhogv8K+byjs2LDvU48sx4/CNHWi26g==\"");
	ShExecInfo.lpDirectory = NULL;
	ShExecInfo.nShow = SW_HIDE;
	ShExecInfo.hInstApp = NULL;
	ShellExecuteEx(&ShExecInfo);
	WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
}

BOOL CPanoHelper::ValidatePanoNumber(IN LPCTSTR szUrl)
{
	BOOL bResult = FALSE;

	TCHAR szAgent[] = _T("");
	HINTERNET hInternet1 = InternetOpen(_T("Microsoft Internet Explorer"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL);
	if (NULL == hInternet1)
	{
		InternetCloseHandle(hInternet1);
		return bResult;
	}
	HINTERNET hInternet2 = InternetOpenUrl(hInternet1, szUrl, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, NULL);
	if (NULL == hInternet2)
	{
		InternetCloseHandle(hInternet2);
		InternetCloseHandle(hInternet1);
		return bResult;
	}

	char szBuffer[1024] = { 0 };
	DWORD dwByteRead = 0;

	if (InternetReadFile(hInternet2, szBuffer, 1023, &dwByteRead) && dwByteRead > 0)
	{
		if (dwByteRead >= 1 && szBuffer[0] == '1')
			bResult = TRUE;
		ZeroMemory(szBuffer, sizeof(szBuffer));
	}
	InternetCloseHandle(hInternet2);
	InternetCloseHandle(hInternet1);

	return bResult;
}

BOOL CPanoHelper::GetValidateNumber(LPCTSTR file, LPTSTR validate_number, SIZE_T validate_number_size)
{
	BOOL bResult = FALSE;

	CMarkup xmlFile;
	if (!xmlFile.Load(file))
		return bResult;

	if (xmlFile.FindChildElem(_T("customid")))
	{
		_tcscat_s(validate_number, validate_number_size, xmlFile.GetChildData().c_str());
		bResult = TRUE;
	}
	return bResult;
}

VOID CPanoHelper::MakePano(LPCTSTR pano_exe_path, LPCTSTR pano_exe_param)
{
	SHELLEXECUTEINFO ShExecInfo = { 0 };
	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
	ShExecInfo.hwnd = NULL;
	ShExecInfo.lpVerb = NULL;
	ShExecInfo.lpFile = pano_exe_path;
	ShExecInfo.lpParameters = pano_exe_param;
	ShExecInfo.lpDirectory = NULL;
	ShExecInfo.nShow = SW_HIDE;
	ShExecInfo.hInstApp = NULL;
	ShellExecuteEx(&ShExecInfo);
	WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
}